import fs from 'fs';
import path from 'path';
import dotenv from 'dotenv';
import express from 'express';
import unzipper from 'unzipper';
import base64ToBlob from './scripts/decodeBase64.js';

dotenv.config({ path: path.join('./', 'src', 'plugins', '.env'), debug: true });

const upload_path = path.join('./', 'src', 'plugins', 'uploads');


export const router = express.Router();

// /api/selfs/blance
router.post('/balance', async function (req, res) {
    try {
        if (!req.body.custom_url) {
            return res.json({
                status: 'error',
                message: '缺少必要参数,请检查API端点!',
            });
        }
        const secrets_content = fs.readFileSync(`${req.user.directories.root}/secrets.json`, 'utf-8');
        const secrets = JSON.parse(secrets_content);
        const custom_key_list = secrets.api_key_custom;
        let authorization = 'Bearer ';
        for (const custom_key of custom_key_list) {
            if (custom_key.active) {
                authorization += custom_key.value;
            }
        }
        const result = {};
        let response = await fetch(`${req.body.custom_url}/dashboard/billing/subscription`, {
            headers: {
                'Authorization': authorization,
                'Content-Type': 'application/json',
            },
        });
        if (!response.ok) {
            throw new Error('查询时出现错误,请检查API配置!');
        }
        let data = await response.json();
        result['subscription_info'] = data;
        response = await fetch(`${req.body.custom_url}/dashboard/billing/usage`, {
            headers: {
                'Authorization': authorization,
                'Content-Type': 'application/json',
            },
        });
        if (!response.ok) {
            throw new Error('查询时出现错误,请检查API配置!');
        }
        data = await response.json();
        result['usage_info'] = data;
        result['success'] = true;
        result['balance'] = (result['subscription_info']['system_hard_limit_usd'] * 100 - result['usage_info']['total_usage']) / 100;
        result['balance_formatted'] = '$' + `${result['balance']}`;
        result['hard_limit_usd'] = result['subscription_info']['hard_limit_usd'];
        result['total_usage_cents'] = result['usage_info']['total_usage'];
        result['total_usage_usd'] = result['usage_info']['total_usage'] / 100;
        result['has_payment_method'] = true;
        return res.json(result);
    } catch (error) {
        return res.json({
            status: 'error',
            message: error.message,
        });
    }
});

// /api/selfs/upload
router.post('/upload', async function (req, res) {
    try {
        const data = base64ToBlob(req.body.chunkData);
        const file_path = path.join(upload_path, `${req.user.profile.handle}.zip`);
        const arrayBuffer = await data.arrayBuffer();
        const buffer = Buffer.from(arrayBuffer);
        if (req.body.chunkIndex === 1) {
            fs.access(file_path, fs.constants.F_OK, (err) => {
                if (!err) {
                    // 文件存在，删除它
                    fs.unlinkSync(file_path);
                } else {
                    // 文件不存在，不执行删除操作
                    console.log('文件不存在');
                }
            });
            // 删除指定文件夹下的所有文件
            fs.readdirSync(req.user.directories.root).forEach((file) => {
                const curPath = path.join(req.user.directories.root, file);
                if (fs.lstatSync(curPath).isDirectory()) {
                    // 递归删除子文件夹
                    fs.rmSync(curPath, { recursive: true, force: true });
                }
            });
        }

        // 创建可写流
        const writeStream = fs.createWriteStream(file_path, {
            flags: 'a', // 'a' 表示追加，'w' 表示覆盖
            encoding: 'utf8',
        });

        // 监听流错误
        writeStream.on('error', (err) => {
            console.error('写入流错误:', err);
            throw new Error('文件上传出错!');
        });

        // 写入数据并等待完成
        await new Promise((resolve, reject) => {
            writeStream.write(buffer, (err) => {
                if (err) {
                    console.error('写入数据错误:', err);
                    reject(err);
                } else {
                    // 关闭流
                    writeStream.end();
                    resolve('数据写入完成');
                }
            });
        });

        // 检查是否所有分片都已上传完成
        const isLastChunk = parseInt(req.body.chunkIndex) === parseInt(req.body.totalChunks) - 1;
        if (isLastChunk) {
            fs.createReadStream(file_path)
                .pipe(unzipper.Extract({ path: req.user.directories.root }))
                .on('error', (err) => {
                    console.error(err);
                })
                .on('finish', () => {
                    return res.json({ status: 'success', message: '文件上传完毕!' });
                })
                .on('close', () => {
                    fs.unlinkSync(file_path);
                });
        } else {
            // 处理分片数据
            return res.json({ status: 'success' });
        }
    } catch (error) {
        console.error('上传过程出错:', error);
        return res.status(500).json({ status: 'error', message: error.message });
    }
});
